<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="所属服务" prop="serviceCode">
          <ft-dict-select v-model="listQuery.param.serviceCode" dict-type="service_name" placeholder="所属服务" style="width: 100%;" clearable class="filter-item" @change="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="listQuery.param.jobName" placeholder="任务名称" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="任务状态" prop="jobStatus">
          <el-select v-model="listQuery.param.jobStatus" placeholder="任务状态" style="width: 207px;" class="filter-item" @change="handleFilterQuery">
            <el-option key="RUNNING" label="运行" value="RUNNING" />
            <el-option key="STOP" label="停止" value="STOP" />
            <el-option key="PAUSE" label="暂停" value="PAUSE" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 150px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="所属服务" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.serviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务分组" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.jobGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.jobName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务描述" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.jobDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" min-width="70px" align="left">
        <template v-slot="{row}">
          <span v-if="row.jobType === 'BATCH'">批量</span>
          <span v-else>默认</span>
        </template>
      </el-table-column>
      <el-table-column label="cron表达式" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.jobCron }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" min-width="80px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.jobStatus === 'RUNNING'" type="success">运行</el-tag>
          <el-tag v-else-if="row.jobStatus === 'PAUSE'">暂停</el-tag>
          <el-tag v-else type="info">停止</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.pause" command="pause"><i class="el-icon-video-pause"> 暂停</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.resume" command="resume"><i class="el-icon-video-play"> 恢复</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.start" command="start"><i class="el-icon-check"> 启动</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.stop" command="stop"><i class="el-icon-close"> 停止</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.trigger" command="trigger"><i class="el-icon-caret-right"> 触发</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.resolve" command="resolve"><i class="el-icon-thumb"> 补偿</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 编辑页面 -->
    <el-dialog :title="title[state]" :visible.sync="visible" :close-on-click-modal="false" width="800px" @close="handleClose">
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属服务" prop="serviceCode">
              <ft-dict-select v-model="formData.serviceCode" dict-type="service_name" placeholder="所属服务" style="width: 100%;" clearable class="filter-item" @change="handleServiceNameChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="jobType">
              <el-select v-model="formData.jobType" class="filter-item" style="width: 100%;" placeholder="请选择" clearable>
                <el-option key="DEFAULT" label="默认" value="DEFAULT" />
                <el-option key="BATCH" label="批量" value="BATCH" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="jobGroup">
              <span slot="label">
                <el-tooltip content="Job所在服务在注册中心的名称" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                任务分组
              </span>
              <el-input v-model="formData.jobGroup" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="jobName">
              <span slot="label">
                <el-tooltip content="需要执行的job名称或者批量的jobId" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
                任务名称
              </span>
              <el-input v-model="formData.jobName" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="cron表达式" prop="jobCron">
              <el-input v-model="formData.jobCron" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务描述" prop="jobDesc">
              <el-input v-model="formData.jobDesc" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="告警邮件" prop="email">
              <el-input v-model="formData.email" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="告警手机" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-radio v-model="formData.status" label="Y">启用</el-radio>
              <el-radio v-model="formData.status" label="N">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div v-if="state !=='detail'" slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="handleClose">
          取消
        </el-button>
        <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
          <span v-if="!submitting">确认</span>
          <span v-else>提 交 中...</span>
        </el-button>
      </div>
    </el-dialog>

    <!--补偿处理-->
    <job-resolve ref="jobResolve" :resolve-params="resolve" />

    <!--详情页面-->
    <!--按需补充-->

  </div>
</template>

<script>
import { handlePageList, handleSave, handleDelete, handlePause, handleResume, handleStart, handleStop, handleTrigger } from './api'
import permission from '@/directive/permission' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import JobResolve from './resolve.vue'
import FtDictSelect from '@/views/components/FtDictSelect/index.vue'

export default {
  // 当前页面名称（组件）
  name: 'JobInfo',
  // 引用组件
  components: { FtDictSelect, Pagination, JobResolve },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          serviceName: undefined,
          jobName: undefined,
          jobStatus: undefined,
          status: undefined
        }
      },
      // 状态字典
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      visible1: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        add: ['task:qrtz:add'],
        edit: ['task:qrtz:edit'],
        del: ['task:qrtz:del'],
        pause: ['task:qrtz:pause'],
        resume: ['task:qrtz:resume'],
        start: ['task:qrtz:stop'],
        stop: ['task:qrtz:stop'],
        trigger: ['task:qrtz:trigger'],
        resolve: ['task:qrtz:pause']
      },
      submitting: false,
      // 表单校验规则
      rules: {
        // 按需补充
        serviceCode: [{ required: true, message: '所属服务不能为空', trigger: 'change' }],
        jobName: [{ required: true, message: '任务名称不能为空', trigger: 'change' }],
        jobType: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
        jobGroup: [{ required: true, message: '任务分组不能为空', trigger: 'change' }],
        jobTarget: [{ required: true, message: '执行目标不能为空', trigger: 'change' }],
        jobCron: [{ required: true, message: 'cron表达式不能为空', trigger: 'change' }],
        jobDesc: [{ required: true, message: '任务描述不能为空', trigger: 'change' }]
      },
      // 详情data
      detail: {
        visible: false,
        data: {}
      },
      // 补偿处理
      resolve: {
        visible: false,
        formData: {}
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      handlePageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 重置表单
    handleRestFormData() {
      // 按需补充
      this.formData = {
        id: undefined,
        serviceName: undefined,
        jobName: undefined,
        jobType: 'DEFAULT',
        jobGroup: undefined,
        jobTarget: undefined,
        jobCron: undefined,
        jobDesc: undefined,
        email: undefined,
        mobile: undefined,
        status: 'Y',
        remark: ''
      }
    },
    handleServiceNameChange(data) {
      this.formData.serviceName = data.label
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 删除
      if (item === 'del') {
        if (row.jobStatus !== 'STOP') {
          this.$message({
            showClose: true,
            message: '删除任务请先停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleDelete(row, index)
        }
      }
      // 暂停
      if (item === 'pause') {
        if (row.jobStatus === 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else if (row.jobStatus === 'PAUSE') {
          this.$message({
            showClose: true,
            message: '当前任务已是暂停状态！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handlePause(row, index)
        }
      }
      // 恢复
      if (item === 'resume') {
        if (row.jobStatus === 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else if (row.jobStatus === 'RUNNING') {
          this.$message({
            showClose: true,
            message: '当前任务已是运行状态！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleResume(row, index)
        }
      }
      // 启动
      if (item === 'start') {
        console.log('88888')
        if (row.jobStatus !== 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已启动，不能重复操作！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleStart(row, index)
        }
      }
      // 停止
      if (item === 'stop') {
        if (row.jobStatus === 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleStop(row, index)
        }
      }
      // 触发
      if (item === 'trigger') {
        if (row.jobStatus === 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleTrigger(row, index)
        }
      }
      // 补偿
      if (item === 'resolve') {
        if (row.jobStatus === 'STOP') {
          this.$message({
            showClose: true,
            message: '当前任务已停止下线！',
            type: 'warning',
            duration: 2000
          })
        } else {
          this.handleResolve(row, index)
        }
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate(row) {
      if (row.jobStatus !== 'STOP') {
        this.$message({
          showClose: true,
          message: '修改任务请先停止下线！',
          type: 'warning',
          duration: 2000
        })
        return
      }
      this.state = 'update'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)

      // 按需补充
      // 清理掉多余的属性值，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail(row) {
      // this.detail.visible = true
      // this.detail.data = Object.assign({}, row)
      // this.$nextTick(() => {
      //   this.$refs['formDetail'].init()
      // })
    },
    // 暂停
    handlePause(row) {
      handlePause({ jobName: row.jobName, jobGroup: row.jobGroup }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 恢复
    handleResume(row) {
      handleResume({ jobName: row.jobName, jobGroup: row.jobGroup }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 启动
    handleStart(row) {
      console.log(9999)
      handleStart({ jobName: row.jobName, jobGroup: row.jobGroup }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 停止
    handleStop(row) {
      handleStop({ jobName: row.jobName, jobGroup: row.jobGroup }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 触发
    handleTrigger(row) {
      handleTrigger({ jobName: row.jobName, jobGroup: row.jobGroup }).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 补偿
    handleResolve(row) {
      this.resolve.visible = true
      this.resolve.formData = Object.assign({}, row)
      this.$nextTick(() => {
        this.$refs['jobResolve'].init()
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ id: row.id }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitting = true
          handleSave(this.formData).then((res) => {
            this.submitting = false
            //  刷新table
            this.handleFilterQuery()
            this.handleClose()
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 关闭弹出层
    handleClose() {
      // this.$refs['dataForm'].resetFields()
      this.handleRestFormData()
      this.visible = false
    }
  }
}
</script>
